package com.scau.service.Impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scau.dao.CommentDao;
import com.scau.dao.MessageDao;
import com.scau.pojo.Message;
import com.scau.service.MessageService;
@Service
public class MessageServiceImpl implements MessageService{
	@Autowired
	MessageDao messageDAO;

	@Override
	public List<Message> query() {
		return messageDAO.query();
	}
	
	@Autowired
	CommentDao commentDao;

	@Override
	public List<Message> queryBySeId(int seId) {
		return messageDAO.queryBySeId(seId);
	}

	@Override
	public int deleteMessageById(int msId) {
		return messageDAO.deleteMessageByMsId(msId);
	}

	@Override
	public int addMessage(JSONObject jsonObject) {
		Message message=new Message();
		int seId=jsonObject.getIntValue("seId");
		int userId=jsonObject.getIntValue("userId");
		String userType=jsonObject.getString("userType");
		String content=jsonObject.getString("content");
		message.setMsContent(content);
		message.setSeId(seId);
		message.setUserId(userId);
		message.setUserType(userType);
		message.setMsReleasetime(new Date());
		message.setMsModifytime(new Date());
		return messageDAO.addMessage(message);
	}
	
	@Override
	public int update(JSONObject jsonObject) {
		int result=0;
		Message message=new Message();
		int msId=jsonObject.getInteger("id");
		String content=jsonObject.getString("content");
		message.setMsId(msId);
		message.setMsContent(content);
		try {
			result=messageDAO.updateMessageById(message);
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;
	}

	@Override
	public int deleteMessages(JSONArray jsonArray) {
		int result1=0;
		int result2=0;
		int result=0;
		int commentCount=0;
		List<Integer> idArr=JSON.parseArray(jsonArray.toString(), Integer.class);
		try {
			for(int id : idArr){
				commentCount=commentDao.getCommentCount(id);
				if(commentCount==0){
					result=messageDAO.deleteMessageByMsId(id);
					System.out.println("result1="+result);
					break;
				}else{
					result1=messageDAO.deleteMessageByMsId(id);
					result2=commentDao.delCommentByMsId(id);
					if(result1==1&&result2!=0){
						result=1;
					}
					System.out.println("result1="+result1+"result2="+result2+"result="+result);
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		return result;
	}

}
